package io.unicorn.modules.water.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import io.unicorn.common.excelutils.ExcelListener;
import io.unicorn.common.exception.RRException;
import io.unicorn.common.utils.DateUtils;
import io.unicorn.common.utils.ExcelUtils;
import io.unicorn.common.validator.ValidatorUtils;
import io.unicorn.commons.dynamic.datasource.annotation.DataSource;

import io.unicorn.modules.progress.entity.ProgressSingleton;
import io.unicorn.modules.sys.entity.SysDeptEntity;
import io.unicorn.modules.sys.entity.SysUserEntity;
import io.unicorn.modules.sys.service.SysDeptService;
import io.unicorn.modules.sys.shiro.ShiroUtils;
import io.unicorn.modules.water.entity.MeterArchivesEntity;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.unicorn.modules.water.entity.TAccountManageEntity;
import io.unicorn.modules.water.service.TAccountManageService;
import io.unicorn.common.utils.PageUtils;
import io.unicorn.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * ${comments}
 *
 * @author LNCG
 * @email LNCG@USTL.EDU.CN
 * @date 2021-04-10 10:01:48
 */
@RestController
@RequestMapping("water/taccountmanage")
public class TAccountManageController {
    @Autowired
    private TAccountManageService tAccountManageService;

    @Autowired
    private SysDeptService sysDeptService;

    @RequestMapping("/status")
    //@RequiresPermissions("water:taccountmanage:list")
    public R status(@RequestParam Map<String, Object> params){
        List<Map<String,Object>> page = tAccountManageService.selectViewAccountExceed(params);

        return R.ok().put("page", page);
    }

    @RequestMapping("/statussuball")
    //@RequiresPermissions("water:taccountmanage:list")
    public R statussuball(@RequestParam Map<String, Object> params){

        List<Map<String,Object>> page = tAccountManageService.selectViewAccountExceedSub(params);

        return R.ok().put("page", page);
    }

    @RequestMapping("/statussub")
    //@RequiresPermissions("water:taccountmanage:list")
    public R statussub(@RequestParam Map<String, Object> params){

        SysUserEntity user = ShiroUtils.getUserEntity();
        SysDeptEntity dept = sysDeptService.getById(user.getDeptId());
        Long deptId =  Long.parseLong(dept.getOrderNum().toString());
        params.put("dept",deptId);

        List<Map<String,Object>> page = tAccountManageService.selectViewAccountExceedSub(params);

        return R.ok().put("page", page);
    }


    /**
     *
     * 2023.3.29 分所数据大屏
     */

    @RequestMapping("/chartdatasuo")
    //@RequiresPermissions("water:taccountmanage:list")
    public R chartDataSuo(@RequestParam Map<String, Object> params){

        SysUserEntity user = ShiroUtils.getUserEntity();
        SysDeptEntity dept = sysDeptService.getById(user.getDeptId());
        Long deptId =  Long.parseLong(dept.getOrderNum().toString());
        params.put("dept",deptId);

        List<Map<String,Object>> page = tAccountManageService.execGetChartData(params);

        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("water:taccountmanage:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = tAccountManageService.queryPage(params);

        return R.ok().put("page", page);
    }

    @RequestMapping("/listerr")
    @RequiresPermissions("water:taccountmanage:list")
    public R listError(@RequestParam Map<String, Object> params){
        PageUtils page = tAccountManageService.getClientErrorDataByProcedure(params);

        return R.ok().put("page", page);
    }
    /**
     * 信息
     */
    @RequestMapping("/info/{proName}")
    @RequiresPermissions("water:taccountmanage:info")
    public R info(@PathVariable("proName") String proName){
        TAccountManageEntity tAccountManage = tAccountManageService.getById(proName);

        return R.ok().put("tAccountManage", tAccountManage);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("water:taccountmanage:save")
    public R save(@RequestBody TAccountManageEntity tAccountManage){
        tAccountManageService.save(tAccountManage);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("water:taccountmanage:update")
    public R update(@RequestBody TAccountManageEntity tAccountManage){
        ValidatorUtils.validateEntity(tAccountManage);
        tAccountManageService.updateById(tAccountManage);
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("water:taccountmanage:delete")
    public R delete(@RequestBody String[] proNames){
        tAccountManageService.removeByIds(Arrays.asList(proNames));

        return R.ok();
    }

    @RequestMapping("/export")
    @RequiresPermissions("water:vaccountmanage:list")
    public void export(@RequestParam Map<String, Object> params,
                       HttpServletRequest request,
                       HttpServletResponse repsonse){
        JSONObject jsonObject = JSONObject.parseObject((String)params.get("params"));

        PageUtils page = tAccountManageService.queryPage(jsonObject);
        List<?> listEntity = page.getList();

        ExcelUtils.exportXlsx(
                repsonse,
                "export",
                "io.unicorn.modules.water.entity.TAccountManageEntity",
                listEntity);
    }

    @RequestMapping("/downloadtemplate")
    public void genExcelTemplate(HttpServletResponse response) throws IOException {
        byte[] data = tAccountManageService.genExcelTemplate();

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"template_"+ DateUtils.format(new Date(),"yyyyMMddHHmmss") +".xlsx\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }

    @RequestMapping("/downloadmap")
    @RequiresPermissions("water:vaccountmanage:list")
    public void downloadmap(@RequestParam Map<String, Object> params,
                       HttpServletRequest request,
                       HttpServletResponse response) throws IOException {
        JSONObject jsonObject = JSONObject.parseObject((String)params.get("params"));

        TAccountManageEntity tAccountManageEntity =  tAccountManageService.getById(jsonObject.getString("key"));
        String filepath = tAccountManageEntity.getDesc20();

        //byte[] data = tAccountManageService.genExcelTemplate();

        // path是指欲下载的文件的路径。
        File file = new File(filepath);
        // 取得文件名。
        String filename = file.getName();
        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(filepath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();

        // 清空response
        response.reset();
        // 设置response的Header
        String downfilename = URLEncoder.encode(filename, "UTF-8");

        response.addHeader("Content-Disposition", "attachment;filename=" + downfilename);
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();


        /*
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"template_"+ DateUtils.format(new Date(),"yyyyMMddHHmmss") +".xlsx\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
        */
    }

    @PostMapping("/importmap")
    @ResponseBody
    @RequiresPermissions("water:taccountmanage:update")
    public R importMap(
            @RequestParam("mymap") MultipartFile file,
            @RequestParam("deptname") String imgsrc,
            HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        String filePath = "C://Users//chenguang//Desktop//map";    //跟路径为本地D盘的test文件夹
        if(StringUtils.isNotBlank(imgsrc)){    //判断路径是否为空，如果不为空，说明已经有了一张图片，那我点击上传文件按钮就要替换掉这张图片，为了不占电脑容量，同时要删掉本地文件
            String initPicPath = filePath + imgsrc;
            File initFile = new File(initPicPath);
            if(initFile.exists() && initFile.isFile()){
                initFile.delete();    //删除文件
            }
        }

        //  以下为创建新存储的文件路径
        String upimages = "/upimage";
        String uuidFileName = "/" + DateUtils.format(new Date(),"yyyyMMddHHmmss") +"_" + imgsrc + "_" + fileName;//UUID.randomUUID().toString()
        String localPath = filePath + upimages;
        File upimagesFile = new File(localPath);  // 没有D://test/upimage文件夹的话就新疆文件夹
        if (!upimagesFile.exists()) {
            upimagesFile.mkdirs();
        }
        String localFilePath = localPath + uuidFileName;
        File picFile = new File(localFilePath);   //创建图片文件
        if (!picFile.exists()) {
            picFile.createNewFile();
        }
        file.transferTo(picFile);   //保存文件

        TAccountManageEntity tAccountManageEntity  = new TAccountManageEntity();
        tAccountManageEntity.setProName(imgsrc);
        tAccountManageEntity.setDesc20(localFilePath);
        tAccountManageService.updateById(tAccountManageEntity);

        return R.ok().put("url",imgsrc+"=="+fileName);
    }


    @PostMapping("/importExcel")
    @RequiresPermissions("water:taccountmanage:update")
    public R importExcel(@RequestParam("myfile") MultipartFile myFile,HttpServletRequest request){
        if (myFile.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        String fileName = myFile.getOriginalFilename();//  获取文件名
        //String suffix = myFile.getOriginalFilename().substring(myFile.getOriginalFilename().lastIndexOf("."));
        //Integer nums = meterArchivesService.importExcel(myFile);

        String id = request.getSession().getId() + fileName;
        AtomicReference<Integer> progress = new AtomicReference<>(0);
        ProgressSingleton.put(id + "Progress", progress);

        try {
            EasyExcel.read(myFile.getInputStream(), TAccountManageEntity.class, new ExcelListener(p -> {
                //保存逻辑（可封装一个普通的sevice）p-为我们执行函数时传入的list
                //sendAddressService.importExcel(p);
                p.stream().forEach(obj->{
                    ((TAccountManageEntity)obj).setUpdatepardate(new Date());

                    System.out.println((TAccountManageEntity)obj);

                    progress.getAndSet(progress.get() + 1);
                    ProgressSingleton.put(id + "Progress", progress);
                });

                try {
                    tAccountManageService.saveOrUpdateBatch(p);
                }catch(Exception e){
                    throw new RRException(e.toString(),e);
                }
            })).sheet().doRead();
        }catch (Exception e) {
            throw  new RRException(e.toString(),e);
        }

        ProgressSingleton.remove(id + "Progress");

        //直接重新运行数量 2023.5.22
        tAccountManageService.execProCalDevCount(null);


        return R.ok().put("url",fileName);
    }

    @RequestMapping("/caldevicecount")
    @RequiresPermissions("water:tclientinfo:update")
    public R execCalDeviceCount(@RequestParam Map<String, Object> params,HttpServletResponse response){
        tAccountManageService.execProCalDevCount(params);
        return R.ok();
    }

    @RequestMapping("/syncnmvpdevice")
    @RequiresPermissions("water:taccountmanage:update")
    public R syncData(@RequestParam Map<String, String> params){//

        String strParam = params.get("proName");
        strParam = strParam.substring(2,strParam.length()-2).replace("\"","");
        String[] arrParam = strParam.split(",");

        for(int i = 0; i < arrParam.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("proName",arrParam[i]);
            List<Map<String, Object>> page = tAccountManageService.exeProSynData(map);
        }
        //System.out.print(params);

        return R.ok().put("data", Arrays.toString(arrParam));
    }

    @RequestMapping("/syncdevicegx")
    @RequiresPermissions("water:taccountmanage:update")
    public R syncDataGx(@RequestParam Map<String, String> params){
        //List<Map<String,Object>> page = tAccountManageService.exeProSynDataGx(params);
        //System.out.print(params);
        String strParam = params.get("proName");
        strParam = strParam.substring(2,strParam.length()-2).replace("\"","");
        String[] arrParam = strParam.split(",");

        for(int i = 0; i < arrParam.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("proName",arrParam[i]);
            List<Map<String, Object>> page = tAccountManageService.exeProSynDataGx(map);
        }
        return R.ok().put("data", strParam);
    }
}
